﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Transactions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

public partial class Admin_Components_SaleOrder_SaleOrder : System.Web.UI.UserControl
{
    DBDataContext db = LINQUtil.GetDBWriteOnly();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.txtCustomerCode.Focus();
            loadDataForm();
            LoadFormForCustomerTab();
            //Session["Cus"] = null;

            //Edit
            string Task = Session["Task"] == null ? "" : Session["Task"].ToString();

            if (Session["SaleOrderID"] != null && !String.IsNullOrEmpty(Session["SaleOrderID"].ToString()) && Task == "EditSO")
            {
                int ID = Convert.ToInt32(Session["SaleOrderID"]);
                ViewState["SaleOrderID"] = ID;
                
                Session["SaleOrderID"] = null;
                Session.Remove("SaleOrderID");
                Session["Task"] = null;
                Session.Remove("Task");
                  
                loadDataView(ID);
            }
            else if (Session["SaleOrderRequestID"] != null && !String.IsNullOrEmpty(Session["SaleOrderRequestID"].ToString()) && Task == "createSOFromSOR")//tao don hang tu don dat hang
            {
                int ID = Convert.ToInt32(Session["SaleOrderRequestID"]);
                ViewState["SaleOrderRequestID"] = ID;
                Session["SaleOrderRequestID"] = null;
                Session.Remove("SaleOrderRequestID");
                Session["Task"] = null;
                Session.Remove("Task");
                loadDataViewFromSOR(ID);
            }
            else
            {
                dtpReceiptDate.SelectedDate = DateTime.Now.Date;
                dtpReceiptDate.MinDate = DateTime.Now;
                TabStrip1.Tabs[1].Selected = true;
                RadMultiPag1.SelectedIndex = 1;
            }
           
            loadDataGrid();
        }
        /*
        if (Session["Cus"] != null)
        {
            string customer = Session["Cus"].ToString();
            this.txtCustomerCode.Text = customer.Split('@')[0].ToString();
            this.txtCustomerName.Text = customer.Split('@')[1].ToString();
            RadWindowManager.Windows.Clear();
        }
         */
    }

    private void loadDataViewFromSOR(int SaleOrderRequestID)
    {
        try
        {
            this.cboFormReceipt.SelectedIndex = 1;
            cboEmployeeDeliveryCode.Enabled = true;
            btnDelivery.Visible = true;
            RadPageView2.Enabled = true;
            RequiredEmployeeDeliveryCode.Enabled = true;

            var sor = (from s in db.SaleOrderRequests
                       join c in db.Customers on s.CustomerID equals c.ID
                       where s.ID == SaleOrderRequestID
                       select new
                       {
                           s.SaleOrderRequestCode,
                           s.Total,
                           s.TotalWeight,
                           s.PhoneNumberReceipt,
                           s.DateTimeReceipt,
                           s.PersonReceipt,
                           s.AddressReceipt,
                           c.CustomerCode,
                           c.CustomerName,
                           s.DiscountAmount,
                           s.CreatedDateTime,
                           s.Amount,
                           s.ShopID,
                           s.SaleOderType,
                          SaleOrderRequestID= s.ID,
                          s.TotalWeightPromotion
                           
                       }).FirstOrDefault();

            txtSaleOrderStatus.Text = "";
            if (sor.ShopID != null)
            {
                cboShop.SelectedValue = (sor.ShopID == null ? 0 : sor.ShopID).ToString();
            }
            txtSaleOrderCode.Text = "";
            txtCustomerCode.Text = sor.CustomerCode;
            txtCustomerName.Text = sor.CustomerName;
            txtSaleOrderRequest.Text = sor.SaleOrderRequestCode;
            txtReceiptAdress.Text = sor.AddressReceipt;
            txtReceiptPerson.Text = sor.PersonReceipt;
            txtReceiptPhoneNumer.Text = sor.PhoneNumberReceipt;
            dtpReceiptDate.SelectedDate = sor.DateTimeReceipt;
            
            ViewState["SaleOrderType"] = sor.SaleOderType;
            string urlImage = Utils.getUrlImage();
            DataTable dtPromotion = new DataTable();
            //Load KM da chon
            
            var listPromotion = db.Promotion_GetForOrderRequest(urlImage, SaleOrderRequestID, int.Parse(this.cboShop.SelectedValue)).ToList();
            dtPromotion = listPromotion.ToDataTable();
            bindingPromotion(dtPromotion);
            ViewState["dtPromotion"] = dtPromotion;

           
            DataTable dt = createDataTable();

           
            var listPackType = db.CodeDetails.ToList().Where(b=>b.CMCode=="PackType" && b.Status == 'A').OrderByDescending(c=>c.CDCode);
           
            var listProductRequest = (from list in db.SaleOrderRequestDetails
                               join p in db.Products on list.ProductID equals p.ID
                               where list.SaleOrderRequestID == SaleOrderRequestID
                               && p.Status == 'A'
                               select new
                               {
                                   list.ProductID,
                                   p.ProductName,
                                   ProductCode = p.ProductCode,
                                   list.Price,
                                   list.Weight,
                                   Total = list.Price * list.Weight,
                                   p.IsPromotion
                               }).ToList();
            foreach (var soDetail in listProductRequest)
            {
                string Weight = soDetail.Weight.ToString();
                int? productID = soDetail.ProductID;
                foreach (var pack in listPackType)
                {
                    int Quantity =int.Parse(Weight) / int.Parse(pack.CDCode);
                    //check ton kho
                    //decimal dQuantity = Math.Round(decimal.Parse(Quantity.ToString()));
                    var ware = db.Warehouses.FirstOrDefault(w => w.ShopID == int.Parse(cboShop.SelectedValue) && w.ProductID == productID && w.PackType == int.Parse(pack.CDCode) && w.Status =='A');
                    int? wareQty = ware == null?0:ware.Quantity;

                    if (wareQty < Quantity && pack.CDCode != "1")//so luong ton kho nho hon thi lay sl ton kho
                    {
                        Quantity = int.Parse(wareQty.ToString());
                    }

                    if (Quantity >= 1)
                    {
                        
                        DataRow drNew = dt.NewRow();
                        drNew["IsPromotion"] = soDetail.IsPromotion;
                        drNew["ProductID"] = soDetail.ProductID;
                        drNew["ProductCode"] = soDetail.ProductCode;
                        drNew["ProductName"] = soDetail.ProductName;
                        drNew["Price"] = String.Format("{0:#,#.##}", soDetail.Price);
                        drNew["Quantity"] = Quantity.ToString();
                        drNew["PackType"] = pack.CDCode;
                        drNew["Weight"] = (int.Parse(drNew["Quantity"].ToString()) * int.Parse(drNew["PackType"].ToString())).ToString();
                        double total = Convert.ToDouble(drNew["Weight"]) * Convert.ToDouble(soDetail.Price);
                        drNew["Total"] = total.ToString();//String.Format("{0:#,#.##}", total); 
                        dt.Rows.Add(drNew);

                        Weight =(double.Parse(Weight) - (double.Parse(drNew["Quantity"].ToString()) * double.Parse(pack.CDCode))).ToString();
                    }
                }
            }
            ViewState["CurrentTable"] = dt;
            // load du lieu tong
            //int totalWeight = Convert.ToInt32(dt.AsEnumerable().Sum(dr => IntOrNull(dr["Weight"])));
            sumWeightSO.InnerText = sor.TotalWeight.ToString();
            sumWeight.InnerText = sor.TotalWeightPromotion.ToString();
           // sumWeight.InnerText = listProductRequest.Where(w => w.IsPromotion == 1).Sum(w => w.Weight).ToString();
            CalsumHelp(DecimalOrNull(sor.Amount), 0, double.Parse(sor.DiscountAmount.ToString()));

            CalcDiscount(DecimalOrNull(sor.Amount), sor.CreatedDateTime);

            //Xet câc button
            dispalyButton('0', "");
            //
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-loadDataViewFromSOR");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }

    private void loadDataView(int SaleOderID)
    {
        try
        {
            var so = db.SaleOrder_ById(SaleOderID, "").FirstOrDefault();

            txtSaleOrderStatus.Text = so.StatusDesc;
            cboShop.SelectedValue = so.ShopID.ToString();
            txtSaleOrderCode.Text = so.SaleOrderCode;
            txtEmployeeBillName.Text = so.CreatedBy;
            txtCustomerCode.Text = so.CustomerCode;
            txtCustomerName.Text = so.CustomerName;
            cboEmployeeDeliveryCode.SelectedValue = so.DeliveryEmployeeID.ToString();
            cboFormReceipt.SelectedValue = so.FormReceipt;
            cboIsReceiptBill.SelectedValue = so.IsReceiptBill == true ? "Y" : "N";

            txtReceiptAdress.Text = so.AddressReceipt;
            txtReceiptPerson.Text = so.PersonReceipt;
            txtReceiptPhoneNumer.Text = so.PhoneNumberReceipt;
            dtpReceiptDate.SelectedDate = so.DateTimeReceipt;
            ViewState["SaleOrderType"] = so.SaleOderType;
            ViewState["SaleOrderRequestID"] = so.SaleOrderRequestID;
            txtSaleOrderRequest.Text = so.SaleOrderRequestCode;
            
             this.cboVAT.Visible = bool.Parse(so.IsReceiptBill.ToString());
            
            string urlImage = Utils.getUrlImage();
            DataTable dtPromotion = new DataTable();
            //Load KM da chon
            var listPromotion = (from sp in db.SaleOrderPromotions
                                 join d in db.PromotionDetails on sp.PromotionDetailID equals d.ID
                                 join p in db.Products on sp.ProductID equals p.ID
                                 where p.ProductType == "P" && p.Status == 'A' && d.Status == 'A'
                                 && sp.SaleOrderID == so.SaleOderID
                                 select new
                                 {
                                     Image = urlImage+p.ImagePath,
                                     sp.ProductID,
                                     sp.PromotionID,
                                     sp.PromotionDetailID,
                                     d.Weight,
                                     p.ProductName,
                                     PromotionQuantity = 0,
                                     PromotionQuantitySelect = sp.QuantitySelect
                                 }).ToList();


            dtPromotion = listPromotion.ToDataTable();
            bindingPromotion(dtPromotion);

            //chi tiet sp
            var listProduct = (from list in db.SaleOrderDetails
                               join p in db.Products on list.ProductID equals p.ID
                               where list.SaleOrderID == SaleOderID
                               && p.Status == 'A'
                               select new
                               {
                                   list.ProductID,
                                   p.ProductName,
                                   ProductCode = p.ProductCode,
                                   list.Price,
                                   list.Weight,
                                   PackType = list.PackType,
                                   Quantity = list.Quantity,
                                   Total = list.Price * list.Weight,
                                   p.IsPromotion
                               }).ToList();

            DataTable dt = listProduct.ToDataTable();
            ViewState["CurrentTable"] = dt;
            // load du lieu tong
            //int totalWeight = Convert.ToInt32(dt.AsEnumerable().Sum(dr => IntOrNull(dr["Weight"])));
            sumWeight.InnerText = so.TotalWeightPromotion.ToString();
            sumWeightSO.InnerText = so.TotalWeight.ToString();
            //sumWeight.InnerText = listProduct.Where(w=>w.IsPromotion == 1).Sum(w => w.Weight).ToString();

            CalsumHelp(DecimalOrNull(so.Amount), decimal.Parse(so.VAT.ToString()), double.Parse(so.DiscountAmount.ToString()));

            DivDiscountAmount.InnerText = so.DiscountAmount.ToString();//Giam gia
            DivConvertedAmount.InnerText = so.ConvertedAmount.ToString(); // tong tien da quy doi
            DivDiscountPromotionDetailID.InnerText = so.PromotionDetailID.ToString();
            DivDiscountPromotionID.InnerText = so.PromotionID.ToString();

            //Xet câc button
            dispalyButton(so.Status, so.FormReceipt);
            //
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-loadDataView");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }

    private void loadDataForm()
    {
        try
        {
           
            Utils.LoadCodeDetail(cboFormReceipt, "FormReceipt", 0);
            cboFormReceipt.SelectedIndex = 0;
            Utils.LoadCodeDetail(cboIsReceiptBill, "ReceiptBill", 0);
            cboIsReceiptBill.SelectedIndex = 1;

            int ShopID = Session["ShopID"] == null ? 0 : int.Parse(Session["ShopID"].ToString());
            Utils.loadEmployeeToCombo(cboEmployeeDeliveryCode, 3, ShopID, 1);
            Utils.loadProductToCombo(cboProduct, 0, "R", ShopID);
            
            txtEmployeeBillName.Text = Session["UserName"].ToString();
            this.cboVAT.Visible = false;
            IsDelivery();

            //Load shop
            int ProvinceID = Session["ProvinceID"] == null ? 0 : int.Parse(Session["ProvinceID"].ToString());
           
            int isShopAll = (ShopID == 0 ? 1 : 0);
            Utils.loadShopByProvinceToCombo(cboShop, isShopAll, ProvinceID, ShopID, "");
            /*
            if (ShopID == 0)//admin
            {
                Utils.loadShopToCombo(cboShop, 1, ShopID,"");
            }
            else
            {
                Utils.loadShopToCombo(cboShop, 0, ShopID,"");
            }
             */ 
            dispalyButton('0', "");

            gvPromotion.DataSource = new DataTable();
            gvPromotion.DataBind();

            gv.DataSource = new DataTable();
            gv.DataBind();
        }
        catch (Exception ex)
        {
           // JavascriptUtil.LoadMessage(UpdatePanel1, false, ex.ToString());
           // Utils.ShowMessageBox(this.Page,ex.ToString());
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-loadDataForm");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }

    private void loadDataGrid()
    {
        try
        {
            DataTable dt = createDataTable();
            if (dt.Rows.Count > 2)
            {
                gvData.Height = 120;
                gvData.ClientSettings.Scrolling.AllowScroll = true;
                gvData.ClientSettings.Scrolling.UseStaticHeaders = true;
            }

            // double sum = 0.0;
            //double discount = 0.0;
            // sumTotal.InnerText = "Tổng tiền thanh toán: " + String.Format("{0:#,#.##}", sum) +" VNĐ";

            //divDiscount.InnerText = "Giảm giá: " + String.Format("{0:#,#.##}", discount) + " VNĐ";

            ViewState["CurrentTable"] = dt;

            gvData.DataSource = dt;
            gvData.DataBind();
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-loadDataGrid");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }

    private DataTable createDataTable(bool isFirst = true)
    {
        DataTable dt = new DataTable();
        if (ViewState["CurrentTable"] == null)
        {
            dt.Columns.Add("ProductID");
            dt.Columns.Add("ProductCode");
            dt.Columns.Add("ProductName");
            dt.Columns.Add("Price");
            dt.Columns.Add("PackType");
            dt.Columns.Add("Quantity");
            dt.Columns.Add("Weight");
            dt.Columns.Add("Total");
            dt.Columns.Add("IsPromotion");
        }
        else
        {
            dt =(DataTable) ViewState["CurrentTable"];
        }
        return dt;
    }

    private SaleOrder createSaleOrderObj()
    {
        SaleOrder saleOrder = new SaleOrder();
        try
        {
            string saleOrderCode = this.txtSaleOrderCode.Text;
            if (saleOrderCode == "")
            {
                //Lay ma sau cung
                int lenZero = 8;//So ky tu khôg tính chữ cái đưungs đầu. ví dụ KH0000001 --> 7, k tính KH
                var CodeMax = db.SaleOrders.Max(d => d.OrderNumber);
                int MaxOrderNumber = (CodeMax == null ? 0 : Convert.ToInt32(CodeMax)) + 1;
                String LastCode = ("00000000" + MaxOrderNumber).ToString();
                String Code = "DH" + LastCode.Substring(LastCode.Length - lenZero);
                //End
                saleOrder.OrderNumber = MaxOrderNumber;
                saleOrder.SaleOderCode = Code;
            }
            else
            {
                saleOrder = db.SaleOrders.FirstOrDefault<SaleOrder>(so => so.SaleOderCode == saleOrderCode);
            }
            var CustomerID = 0;
            if (txtCustomerCode.Text == "")
            {
                Customer cus = createCustomer("2");
                CustomerID = cus.ID;
            }
            else
            {
                CustomerID = (from c in db.Customers where c.CustomerCode == this.txtCustomerCode.Text.Trim() select c.ID).FirstOrDefault();
            }
            if (CustomerID == 0)
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra trong quá trình tạo khách hàng.Vui lòng thử lại!");
                return null;
            }
            saleOrder.SaleOrderRequestID = ViewState["SaleOrderRequestID"] == null ? 0 : int.Parse(ViewState["SaleOrderRequestID"].ToString());
            saleOrder.CustomerID = CustomerID;
            saleOrder.IsReceiptBill = (this.cboIsReceiptBill.SelectedValue.ToLower() == "n" ? false : true);
            saleOrder.DeliveryEmployeeID = (this.cboEmployeeDeliveryCode.SelectedValue == "" ? 0 : Convert.ToInt32(this.cboEmployeeDeliveryCode.SelectedValue));
            saleOrder.FormReceipt = cboFormReceipt.SelectedValue;
            saleOrder.SaleOderType = ViewState["SaleOrderType"] == null ? "S" : ViewState["SaleOrderType"].ToString();
            saleOrder.DiscountAmount = double.Parse(DivDiscountAmount.InnerText);
            saleOrder.Amount = double.Parse(DivAccumulateAmount.InnerText);
            saleOrder.Total = double.Parse(DivSumPayment.InnerText);
            saleOrder.VAT = double.Parse(this.cboIsReceiptBill.SelectedValue.ToLower() == "n" ? "0" : this.cboVAT.SelectedValue);
            saleOrder.ShopID = int.Parse(cboShop.SelectedValue);

            saleOrder.TotalWeightPromotion = Convert.ToInt32(sumWeight.InnerText);
            saleOrder.TotalWeight = Convert.ToInt32(sumWeightSO.InnerText);
            //thong tin giao hang
            saleOrder.PersonReceipt = txtReceiptPerson.Text.Trim();
            saleOrder.PhoneNumberReceipt = txtReceiptPhoneNumer.Text.Trim();
            saleOrder.AddressReceipt = txtReceiptAdress.Text.Trim();
            saleOrder.DateTimeReceipt = dtpReceiptDate.SelectedDate;

            saleOrder.CreatedBy = Session["UserName"].ToString();
            saleOrder.LastUpdatedBy = Session["UserName"].ToString();
            saleOrder.CreatedDateTime = DateTime.Now;
            saleOrder.LastUpdatedDateTime = DateTime.Now;
            saleOrder.Status = 'N';
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-createSaleOrderObj");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
        return saleOrder;
    }
    protected void cboShop_SelectedIndexChanged(object sender, EventArgs e)
    {
        int ShopID = Session["ShopID"] == null ? 0 : int.Parse(Session["ShopID"].ToString());
        Utils.loadEmployeeToCombo(cboEmployeeDeliveryCode, 3, ShopID, 1);
        Utils.loadProductToCombo(cboProduct, 0, "R", int.Parse(this.cboShop.SelectedValue));
        IsDelivery();
    }
  
    private void InsertConvertHistory(int? saleOrderID, int? cusID)
    {
        try
        {
            if (double.Parse(DivDiscountAmount.InnerText) > 0)
            {
                //// Them lich su qui doi diem giam gia
                ConvertHistory convertHistory = new ConvertHistory();
                convertHistory.CustomerID = cusID;
                convertHistory.SaleOrderID = saleOrderID;
                convertHistory.DiscountAmount = double.Parse(DivDiscountAmount.InnerText);
                convertHistory.PromotionDetailID = int.Parse(DivDiscountPromotionDetailID.InnerText);
                convertHistory.PromotionID = int.Parse(DivDiscountPromotionID.InnerText);
                convertHistory.ConvertedAmount = double.Parse(DivConvertedAmount.InnerText);
                convertHistory.Status = 'N';
                convertHistory.LastUpdatedBy = Session["UserName"].ToString();
                convertHistory.LastUpdatedDateTime = DateTime.Now;
                convertHistory.CreatedBy = Session["UserName"].ToString();
                convertHistory.CreatedDateTime = DateTime.Now;
                db.Insert<ConvertHistory>(convertHistory);
            }
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-InsertConvertHistory");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    private void DeleteConvertHistory(int? saleOrderID, int? cusID)
    {
        try
        {
            ConvertHistory convertHistory = db.ConvertHistories.FirstOrDefault<ConvertHistory>(a => a.CustomerID == cusID && a.SaleOrderID == saleOrderID);
            if (convertHistory != null)
            {
                db.Delete<ConvertHistory>(convertHistory);
            }
        }catch(Exception ex){
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-DeleteConvertHistory");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    private void DeletePromotion(int? saleOrderID)
    {
        try
        {
            List<SaleOrderPromotion> saleOrderPromotion = (from sd in db.SaleOrderPromotions where sd.SaleOrderID == saleOrderID select sd).ToList<SaleOrderPromotion>();
            db.Delete<SaleOrderPromotion>(saleOrderPromotion);
        }catch(Exception ex){
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-DeletePromotion");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    private void InsertPromotion(int saleOrderID)
    {
        try
        {
            List<SaleOrderPromotion> listPro = new List<SaleOrderPromotion>();
            foreach (GridDataItem it in gvPromotion.Items)
            {
                SaleOrderPromotion saleOrderPromotion = new SaleOrderPromotion();

                int ProductID = int.Parse(it["ProductID"].Text);
                int PromotionDetailID = int.Parse(it["PromotionDetailID"].Text);
                int PromotionID = int.Parse(it["PromotionDetailID"].Text);
                RadNumericTextBox QuantitySelect = (RadNumericTextBox)it.FindControl("txtQuantitySelect");
                if (int.Parse(QuantitySelect.Text) > 0)
                {
                    saleOrderPromotion.ProductID = ProductID;
                    saleOrderPromotion.SaleOrderID = saleOrderID;
                    saleOrderPromotion.QuantitySelect = int.Parse(QuantitySelect.Text);
                    saleOrderPromotion.PromotionID = PromotionID;
                    saleOrderPromotion.PromotionDetailID = PromotionDetailID;
                    saleOrderPromotion.CreatedBy = Session["UserName"].ToString();
                    saleOrderPromotion.LastUpdatedBy = Session["UserName"].ToString();
                    saleOrderPromotion.CreatedDateTime = DateTime.Now;
                    saleOrderPromotion.LastUpdatedDateTime = DateTime.Now;
                    double? PurchasePrice = (from w in db.Warehouses where w.ProductID == ProductID && w.PackType == 0 && w.ShopID == int.Parse(this.cboShop.SelectedValue) select w.PurchasePrice).FirstOrDefault();
                    saleOrderPromotion.PurchasePrice = PurchasePrice;
                    saleOrderPromotion.Status = 'N';//Moi luu
                    listPro.Add(saleOrderPromotion);
                }
            }
            db.Insert<SaleOrderPromotion>(listPro);
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-InsertPromotion");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    private void DeleteDetail(int? saleOrderID)
    {
        try
        {
            List<SaleOrderDetail> soDetail = (from sd in db.SaleOrderDetails where sd.SaleOrderID == saleOrderID select sd).ToList<SaleOrderDetail>();
            db.Delete<SaleOrderDetail>(soDetail);
        }catch(Exception ex){
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-DeleteDetail");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
       /*
         RadWindowManager.Visible = true;
        // RadWindow1.NavigateUrl = "OderRequestSearchItem.aspx?BranchCode=" + cboBranch.SelectedValue + "&HashCode=" + hiddenHashCode.Value;
        RadWindow1.NavigateUrl = "CustomerPopup.aspx";
        RadWindow1.ID = "Rad1";
        RadWindow1.VisibleOnPageLoad = true;
        RadWindow1.Width = 1100;
        RadWindow1.Height = 400;
        RadWindow1.VisibleStatusbar = false;
        RadWindowManager.Windows.Clear();
        RadWindowManager.Windows.Add(RadWindow1);
        */
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        //RadWindowManager.Windows.Clear();
        
        if (this.cboShop.SelectedValue.Trim() == "0" || this.cboShop.SelectedValue.Trim() == "")
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn cửa hàng");
            this.cboShop.Focus();
            return;
        }

        string productID = "";
        try
        {
            string productIDValue = cboProduct.SelectedValue;
            string productName = cboProduct.SelectedItem.Text;
            string Quantity = txtWeight.Text == "" ? "0" : txtWeight.Text.Replace(",","");
            productID = productIDValue.Split('|')[0];
            string packType = productIDValue.Split('|')[1];
            if (productID == "")
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra. Vui lòng thử lại.");
                return;
            }
            if (productID != "")
            {
                int? warehouseQty = CheckWarehouse(int.Parse(productID), int.Parse(cboShop.SelectedValue), int.Parse(Quantity), int.Parse(packType));
                if (warehouseQty != -1)//so luong ton kho khong du
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Sản phẩm " + productName + " không đủ số lượng tồn kho. SL tồn kho hiện tại:" + warehouseQty.ToString());
                    return;
                }
            }
            if (productID != "")
            {
                if (ViewState["CurrentTable"] != null)
                {
                    DataTable dt = (DataTable)ViewState["CurrentTable"];
                    //check ma san pham da chon chua
                    DataRow[] rows = dt.Select("ProductID='" + productID + "' AND PackType='" + packType + "'");
                    if (rows.Count() > 0)
                    {
                        rows[0].Delete();
                        dt.AcceptChanges();
                        //JavascriptUtil.LoadMessage(UpdatePanel1, false, "Sản phẩm : " + productName + " đã tồn tại. vui lòng chọn sp khác");
                        //return;
                    }

                    var location = db.Shops.FirstOrDefault(s => s.ID == int.Parse(this.cboShop.SelectedValue));

                    if (location == null)
                    {
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Cửa hàng chưa có dữ liệu tỉnh thành");
                        return;
                    }

                    var price = (from pr in db.DefinitionPrices
                                 where pr.Status == 'A'
                                 && pr.ProductID == int.Parse(productID)
                                 && pr.LocationID == location.ProvinceID
                                 select pr).FirstOrDefault();
                    if (price == null)
                    {
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Sản phẩm : " + productName + " chưa có giá bán. vui lòng tạo giá bán ở màn hình sản phẩm");
                        return;
                    }
                    var pro = (from p in db.Products
                               where p.ID == Convert.ToInt32(productID)
                               && p.Status == 'A'
                               select p).FirstOrDefault();

                 
                    if (pro != null)
                    {
                        DataRow drNew = dt.NewRow();

                        drNew["IsPromotion"] = pro.IsPromotion;
                        drNew["ProductID"] = pro.ID;
                        drNew["ProductCode"] = pro.ProductCode;
                        drNew["ProductName"] = pro.ProductName;
                        drNew["Price"] = String.Format("{0:#,#.##}", price.Price);
                        drNew["Quantity"] = Quantity;
                        drNew["PackType"] = packType;
                        drNew["Weight"] = (int.Parse(Quantity) * int.Parse(packType)).ToString();
                        double total = Convert.ToDouble(drNew["Weight"]) * Convert.ToDouble(price.Price);
                        drNew["Total"] = total.ToString();//String.Format("{0:#,#.##}", total); 
                        dt.Rows.Add(drNew);
                        ViewState["CurrentTable"] = dt;
                    }
                    gvData.DataSource = dt;
                    gvData.DataBind();
                    int totalWeight = Convert.ToInt32(dt.AsEnumerable().Where(a => a.Field<string>("IsPromotion") == "1").Sum(dr => IntOrNull(dr["Weight"])));
                    sumWeight.InnerText = totalWeight.ToString();
                    int totalWeightSO = Convert.ToInt32(dt.AsEnumerable().Sum(dr => IntOrNull(dr["Weight"])));
                    sumWeightSO.InnerText = totalWeightSO.ToString();
                    CalSum(dt);

                    DataTable dtPro = loadPromotionPromotion(totalWeight, 0);
                    bindingPromotion(dtPro);

                    btnPayment.Enabled = false;
                    btnReturn.Enabled = false;
                    btnDelivery.Enabled = false;
                }
            }
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("ProductId:" + productID + ", ShopID:" + cboShop.SelectedValue.ToString());
            ControlUtil.LogError("SaleOrder-btnAdd_Click");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    private void bindingPromotion(DataTable dtPro)
    {
        if (dtPro.Rows.Count > 5)
        {
            gvPromotion.Height = 150;
            gvPromotion.ClientSettings.Scrolling.AllowScroll = true;
        }
        gvPromotion.ClientSettings.Scrolling.UseStaticHeaders = true;
        gvPromotion.DataSource = dtPro;
        gvPromotion.DataBind();

    }
    private int? CheckWarehouse(int productID, int shopID, decimal Qty,int packType)
    {
        int? result = -1;
        try
        {
            if (Qty > 0)
            {
                var wh = db.Warehouses.FirstOrDefault<Warehouse>(w => w.ProductID == productID && w.ShopID == shopID &&w.PackType==packType);
                if (wh != null)
                {
                    if (wh.Quantity < Qty)
                    {
                        result = wh.Quantity;
                    }
                }
                else
                {
                    result = 0;
                }
            }
        }catch(Exception ex){
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-CheckWarehouse");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
        return result;
    }
    protected void btnReset_Click(object sender, EventArgs e)
    {
       // RadWindowManager.Windows.Clear();
        Session["Cus"] = null;
        Response.Redirect("~/SaleOrder", true);
        // ViewState["dtPromotion"] = null;
        //loadDataForm();
    }

    protected void RadInput_TextChanged(object sender, EventArgs e)
    {
        try{
       // RadWindowManager.Windows.Clear();
        RadNumericTextBox radNumeric = (RadNumericTextBox)sender;

        string QtySelect = radNumeric.Text == "" ? "0" : radNumeric.Text.Replace(",","");
        GridDataItem dataItem = (GridDataItem)radNumeric.NamingContainer;
        string ProductID = dataItem["ProductID"].Text;
        string ProductName = dataItem["ProductName"].Text;
        string Weight = dataItem["Weight"].Text;
        string GvPromotionQuantity = dataItem["PromotionQuantity"].Text;

        int? a = CheckWarehouse(int.Parse(ProductID), int.Parse(cboShop.SelectedValue), Convert.ToInt32(QtySelect),0);
        if (a != -1)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Quà tặng " + ProductName + " đã hết. Vui lòng chọn quà tặng khác. SL tồn kho: " + a);
            radNumeric.Text = "0";
            return;
        }
        
        int TotalWeightSelect = Convert.ToInt32(QtySelect) * Convert.ToInt32(Weight);
        int totalWeight = Convert.ToInt32(sumWeight.InnerText);
        if (ViewState["dtPromotion"] != null)
        {
            DataTable dtPro = (DataTable)ViewState["dtPromotion"];

            DataRow[] rowArr = dtPro.Select("ProductID='" + ProductID + "'");
            if (Convert.ToInt32(QtySelect) < 0)
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Số lượng chọn không được nhỏ hơn 0");
                radNumeric.Text = "0";
                DataRow row = rowArr[0];
                row["PromotionQuantitySelect"] = "0";
                return;
            }
            if (rowArr.Count() > 0)
            {
                DataRow row = rowArr[0];
                row["PromotionQuantitySelect"] = QtySelect;
            }

            int sumWeightSelected = Convert.ToInt32(dtPro.AsEnumerable().Sum(dr => IntOrNull(dr["Weight"]) * IntOrNull(dr["PromotionQuantitySelect"])));
            int totalWeightRemain = totalWeight - sumWeightSelected;
            if (totalWeightRemain < 0)
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Số lượng chọn không được vượt quá số lượng khuyến mãi");
                radNumeric.Text = "0";
                DataRow row = rowArr[0];
                row["PromotionQuantitySelect"] = "0";
                return;
            }
            int PromotionQuantity = 0;
            foreach (DataRow r in dtPro.Rows)
            {
                PromotionQuantity = totalWeightRemain / Convert.ToInt32(r["Weight"]);
                r["PromotionQuantity"] = PromotionQuantity;
            }
            ViewState["dtPromotion"] = dtPro;
            bindingPromotion(dtPro);
        }
        }catch(Exception ex){
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-RadInput_TextChanged");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }

    protected void txtCustomerCode_TextChanged(object sender, EventArgs e)
    {
        try
        {
           // RadWindowManager.Windows.Clear();
            string Input = this.txtCustomerCode.Text.Trim();
            if (Input != "")
            {
                int lenZero = 7;
                string temp = "0000000" + Input.Replace("KH", "");
                String CustomerCode = "KH" + temp.Substring(temp.Length - lenZero);
                var cus = (from c in db.Customers
                           where c.CustomerCode == CustomerCode
                           || c.PhoneNumber.IndexOf(Input) != -1
                           select c).FirstOrDefault();
                if (cus != null)
                {
                    this.txtCustomerName.Text = cus.CustomerName;
                    this.txtCustomerCode.Text = cus.CustomerCode;
                }
                else
                {
                    this.txtCustomerName.Text = "";
                    this.txtCustomerCode.Text = "";
                }
            }
            else
            {
                this.txtCustomerName.Text = "";
                this.txtCustomerCode.Text = "";
            }
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-txtCustomerCode_TextChanged");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }

    protected void txtCustomerName_TextChanged(object sender, EventArgs e)
    {
        try
        {
            //RadWindowManager.Windows.Clear();
            string Input = this.txtCustomerName.Text.Trim().ToLower();
            if (Input != "")
            {
                var cus = (from c in db.Customers
                           where c.PhoneNumber.IndexOf(Input) != -1
                           || c.CustomerName.ToLower().IndexOf(Input) != -1
                           || c.CustomerCode.ToLower().IndexOf(Input) != -1
                           select c).FirstOrDefault();
                if (cus != null)
                {
                    this.txtCustomerName.Text = cus.CustomerName;
                    this.txtCustomerCode.Text = cus.CustomerCode;
                }
                else
                {
                    this.txtCustomerName.Text = "";
                    this.txtCustomerCode.Text = "";
                    if (txtCustomerCode.Text == "")
                    {
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Khách hàng này không tồn tại. Vui tạo mới khách hàng ơ tab Thông tin khách hàng");
                        RadPageView4.Enabled = true;
                        TabStrip1.SelectedIndex = 1;
                        RadPageView4.Selected = true;
                        return;
                    }
                }
            }
            else
            {
                this.txtCustomerName.Text = "";
                this.txtCustomerCode.Text = "";
            }
        }catch(Exception ex){
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-txtCustomerName_TextChanged");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    private DataTable CreateDataTableSelected()
    {

        DataTable dt = new DataTable();

        if (ViewState["DataTableSelected"] != null)
        {
            dt = (DataTable)ViewState["DataTableSelected"];
        }
        else
        {
            dt.Columns.Add("ProductID");
            dt.Columns.Add("PromotionQuantitySelect");
            dt.Columns.Add("TotalWeight");
            ViewState["DataTableSelected"] = dt;
        }

        return dt;
    }

    private DataTable loadPromotionPromotion(int totalWeight, int totalWeightSelected)
    {
        
        DataTable dtPromotion = createDataTablPromotion();
        try
        {
            int totalWeightRemain = totalWeight - totalWeightSelected;

            if (totalWeight > 0)
            {

                //Lay danh sach sp KM
                DataTable dtProductPromotion = getListProductPromotion();
                int PromotionQuantity = 0;
                foreach (DataRow detail in dtProductPromotion.Rows)
                {
                    PromotionQuantity = totalWeightRemain / Convert.ToInt32(detail["Weight"]);
                    // if (PromotionQuantity > 0)
                    //{
                    DataRow drNew = dtPromotion.NewRow();
                    drNew["ProductID"] = detail["ProductID"];
                    drNew["ProductCode"] = detail["ProductCode"];
                    drNew["ProductName"] = detail["ProductName"];
                    drNew["PromotionDetailID"] = detail["PromotionDetailID"];
                    drNew["Weight"] = detail["Weight"];
                    drNew["PromotionID"] = detail["PromotionID"];
                    drNew["Image"] = detail["Image"];
                    drNew["PromotionQuantity"] = PromotionQuantity;
                    drNew["PromotionQuantitySelect"] = 0;
                    drNew["QuantityStock"] = detail["QuantityStock"];
                    
                    dtPromotion.Rows.Add(drNew);
                    // }
                }
            }
            ViewState["dtPromotion"] = dtPromotion;
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-loadPromotionPromotion");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
           // JavascriptUtil.LoadMessage(UpdatePanel1, false, ex.Message);
        }
        return dtPromotion;
    }

    private DataTable getListProductPromotion()
    {
        DataTable dt = new DataTable();
        try
        {
            string urlImage = Utils.getUrlImage();
            if (CacheUtil.GetCache("ListProductPromotion") == null)
            {
                /*
                DateTime date = DateTime.Now.Date;
                var listPromotion = (from p in db.Promotions
                                     join pd in db.PromotionDetails on p.ID equals pd.PromotionID
                                     join pro in db.Products on pd.ProductID equals pro.ID
                                     where p.Status == 'A' && pd.Status == 'A' && p.PromotionType == "K"
                                     && pro.Status == 'A' && pro.ProductType == "P"
                                     && date >= p.StartDate && date <= p.EndDate
                                     select new
                                     {
                                         ProductID = pd.ProductID,
                                         PromotionID = pd.PromotionID,
                                         PromotionDetailID = pd.ID,
                                         ProductCode = pro.ProductCode,
                                         ProductName = pro.ProductName,
                                         Weight = pd.Weight,
                                         Image = urlImage+ pro.ImagePath
                                     }
                                    ).ToList();
                 */
                var listPromotion = db.Promotion_Get(urlImage, int.Parse(this.cboShop.SelectedValue)).ToList();
                dt = listPromotion.ToDataTable();
                CacheUtil.InsertCache("ListProductPromotion", dt);
            }
            else
            {
                dt = (DataTable)CacheUtil.GetCache("ListProductPromotion");
            }
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-getListProductPromotion");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
        return dt;
    }
    private DataTable createDataTablPromotion()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("ProductID");
        dt.Columns.Add("ProductCode");
        dt.Columns.Add("ProductName");
        dt.Columns.Add("PromotionDetailID");
        dt.Columns.Add("Weight");
        dt.Columns.Add("PromotionID");
        dt.Columns.Add("Image");
        dt.Columns.Add("PromotionQuantity");
        dt.Columns.Add("PromotionQuantitySelect");
        dt.Columns.Add("Info");
        dt.Columns.Add("QuantityStock");
        
        return dt;
    }
    private void CalSum(DataTable dt)
    {
        try
        {
            decimal vat = decimal.Parse(this.cboIsReceiptBill.SelectedValue.ToLower() == "n" ? "0" : this.cboVAT.SelectedValue);

            var sum = dt.AsEnumerable().Sum(dr => DecimalOrNull(dr["Total"]));
            double discount = Convert.ToDouble(CalcDiscount(sum, DateTime.Now.Date));//tinh giam gia
            CalsumHelp(sum, vat, discount);
        }catch(Exception ex){
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-CalSum");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }

    private void CalsumHelp(decimal? sum, decimal vat, double discount)
    {
        try
        {
            double Payment = Convert.ToDouble(sum * (vat + 1)) - discount;
            sumTotal.InnerText = "Tổng: " + String.Format("{0:#,#.##}", sum) + " VNĐ";

            if (vat != 0)
            {
                sumTotalTax.Visible = true;
                sumTotalTax.InnerText = "Sau thuế: " + String.Format("{0:#,#.##}", sum * (vat + 1)) + " VNĐ";
            }
            else
            {
                sumTotalTax.Visible = false;
            }
            sumPayment.InnerText = "Thanh toán: " + String.Format("{0:#,#.##}", Payment) + " VNĐ";
            if (discount > 0)
            {
                divDiscount.InnerText = "Giảm giá: " + String.Format("{0:#,#.##}", discount) + " VNĐ";
            }
            else
            {
                divDiscount.InnerText = "Giảm giá: 0 VNĐ";
            }

            DivSumPayment.InnerText = Payment.ToString();//So tien phai thanh toan
            DivAccumulateAmount.InnerText = sum.ToString();//Tong tien truoc thue
        }catch(Exception ex){
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-CalsumHelp");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    private decimal? CalcDiscount(decimal? total, DateTime? date)
    {

        decimal? Discount = 0;
        try
        {
            var cus = (from c in db.Customers
                       where c.CustomerCode == txtCustomerCode.Text.Trim()
                       select c).FirstOrDefault();
            //if (cus != null)
            // {
            decimal? TotalRemainAmount = DecimalOrNull(cus !=null?cus.RemainAmount:0) + DecimalOrNull(total);

            //Lay so tien duoc huong KM
            // DateTime date = DateTime.Now.Date;
            var promotion = (from p in db.Promotions
                             join pd in db.PromotionDetails on p.ID equals pd.PromotionID
                             where p.Status == 'A' && pd.Status == 'A' && p.PromotionType == "M"
                             && date >= p.StartDate && date <= p.EndDate
                             orderby p.LastUpdatedDateTime descending
                             select new
                             {
                                 Amount = pd.Amount,
                                 DiscountAmount = pd.DiscountAmount,
                                 PromotionID = pd.PromotionID,
                                 PromotionDetailID = pd.ID,
                             }
                           ).FirstOrDefault();
            if (promotion != null)
            {
                int? number = IntOrNull(TotalRemainAmount < DecimalOrNull(promotion.Amount) ? 0 : (IntOrNull(TotalRemainAmount) / IntOrNull(promotion.Amount)));
                Discount = number * DecimalOrNull(promotion.DiscountAmount);//giam gia
                DivDiscountAmount.InnerText = Discount.ToString();//Giam gia
                DivConvertedAmount.InnerText = (number * promotion.Amount).ToString(); // tong tien da quy doi
                DivDiscountPromotionDetailID.InnerText = promotion.PromotionDetailID.ToString();
                DivDiscountPromotionID.InnerText = promotion.PromotionID.ToString();
            }
            // }
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-CalcDiscount");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
        return Discount;
    }
	
    private decimal? DecimalOrNull(object val)
    {
        try
        {
            return Convert.ToDecimal(val);
        }
        catch
        {
            return null;
        }
    }

    private int? IntOrNull(object val)
    {
        try
        {
            return Convert.ToInt32(val);
        }
        catch
        {
            return null;
        }
    }
    protected void grvData_ItemCommand(object sender, GridCommandEventArgs e)
    {

        string commandName = e.CommandName;
        string ProductID_PackType = e.CommandArgument.ToString();
        string ProductID = ProductID_PackType.Split('-')[0];
        string PackType = ProductID_PackType.Split('-')[1];
        if (commandName == "DelItem")
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];

            DataRow[] rows = dt.Select("ProductID='" + ProductID+"' AND PackType='"+PackType+"'");
            foreach (DataRow r in rows)
            {
                r.Delete();
                dt.AcceptChanges();
            }
            ViewState["CurrentTable"] = dt;
            gvData.DataSource = dt;
            gvData.DataBind();

            //tinh lai khuyen mai
            int totalWeight = Convert.ToInt32(dt.AsEnumerable().Where(a=>a.Field<string>("IsPromotion") == "1").Sum(dr => IntOrNull(dr["Weight"])));
            sumWeight.InnerText = totalWeight.ToString();
            CalSum(dt);

            DataTable dtPro = loadPromotionPromotion(totalWeight, 0);
            bindingPromotion(dtPro);
        }
        else if (commandName == "EditItem")
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            DataRow[] rows = dt.Select("ProductID='" + ProductID + "' AND PackType='" + PackType + "'");
            if (rows.Count() > 0)
            {
                this.cboProduct.SelectedValue = ProductID + "|" + PackType;
                this.txtWeight.Text = rows[0]["Quantity"].ToString();
            }
        }

    }

    protected void cboIsReceiptBill_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        string isBill = this.cboIsReceiptBill.SelectedValue;
        decimal vat = decimal.Parse(this.cboIsReceiptBill.SelectedValue.ToLower() == "n" ? "0" : this.cboVAT.SelectedValue);
        if (isBill.ToString().ToLower() == "n")
        {
            this.cboVAT.Visible = false;

        }
        else
        {
            this.cboVAT.Visible = true;
        }
        CalsumHelp(DecimalOrNull(this.DivAccumulateAmount.InnerText == "" ? "0" : this.DivAccumulateAmount.InnerText), vat, double.Parse(this.DivDiscountAmount.InnerText == "" ? "0" : this.DivDiscountAmount.InnerText));
    }

    protected void cboFormReceipt_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        IsDelivery();
    }

    private void IsDelivery()
    {
        if (this.cboFormReceipt.SelectedValue.ToLower() == "s")//Tai cua hang
        {
            cboEmployeeDeliveryCode.Enabled = false;
            btnDelivery.Visible = false;
            RadPageView2.Enabled = false;
            RequiredEmployeeDeliveryCode.Enabled = false;
        }
        else//Tai nha khach hang
        {
            cboEmployeeDeliveryCode.Enabled = true;
            btnDelivery.Visible = true;
            RadPageView2.Enabled = true;
            RequiredEmployeeDeliveryCode.Enabled = true;
        }


    }

    private void dispalyButton(char? Status,String FormReceipt)
    {
        this.btnPrint.Visible = false;
        if (Status != '0')
        {
            gvData.Enabled = true;
            if (Status == 'N') // tao moi
            {
                btnCancel.Enabled = true;
                if (FormReceipt.ToLower() == "s")
                {
                    btnPayment.Enabled = true;
                    btnDelivery.Visible = false;
                }
                else
                {
                    btnPayment.Enabled = false;
                    btnDelivery.Visible = true;
                }
                btnReturn.Enabled = false;
                btnDelivery.Enabled = true;
                this.txtSaleOrderStatus.Text = "Tạo mới";
            }
            else if (Status == 'T')//dang giao hang
            {
                btnSave.Enabled = false;
                btnCancel.Enabled = false;
                btnPayment.Enabled = true;
                btnReturn.Enabled = true;
                btnDelivery.Enabled = false;
                btnAddProduct.Enabled = false;
                btnRefresh.Visible = false;
                lbl.Visible = false;
                this.txtSaleOrderStatus.Text = "Đang giao hàng";
                this.btnPrint.Visible = true;
                gvData.Enabled = false;
            }
            else if (Status == 'C')//đã thanh toán
            {
                btnSave.Enabled = false;
                btnCancel.Enabled = false;
                btnPayment.Enabled = false;
                btnReturn.Enabled = true;
                btnDelivery.Enabled = false;
                btnAddProduct.Enabled = false;
                btnRefresh.Visible = false;
                lbl.Visible = false;
                this.txtSaleOrderStatus.Text = "Đã thanh toán";

                this.btnPrint.Visible = true;
                gvData.Enabled = false;
            }
            else if (Status == 'E')//Hủy bỏ
            {
                btnSave.Enabled = false;
                btnCancel.Enabled = false;
                btnPayment.Enabled = false;
                btnReturn.Enabled = false;
                btnDelivery.Enabled = false;
                btnAddProduct.Enabled = false;
                btnRefresh.Visible = false;
                lbl.Visible = false;
                this.txtSaleOrderStatus.Text = "Hủy bỏ";
                gvData.Enabled = false;
            }

            else if (Status == 'R')//Tra hang
            {
                btnSave.Enabled = false;
                btnCancel.Enabled = false;
                btnPayment.Enabled = false;
                btnReturn.Enabled = false;
                btnDelivery.Enabled = false;
                btnAddProduct.Enabled = false;
                btnRefresh.Visible = false;
                lbl.Visible = false;
                this.txtSaleOrderStatus.Text = "Trả hàng";
                gvData.Enabled = false;
            }

            if (Status == 'E' || Status == 'T' || Status == 'C' || Status == 'R')
            {
                this.RadPageView1.Enabled = false;
                this.RadPageView2.Enabled = false;
                this.RadPageView3.Enabled = false;
            }
        }
        else
        {
            btnCancel.Enabled = false;
            btnPayment.Enabled = false;
            btnReturn.Enabled = false;
            btnDelivery.Enabled = false;
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
       
        using (var transation = new TransactionScope())
        {
            try
            {
                
                if (CheckPromotionSelect() == false)
                {
                    return;
                }

                if (gvData.Items.Count > 0)
                {

                    SaleOrder saleOrder = createSaleOrderObj();
                    if (saleOrder == null)
                    {
                        return;
                    }
                    //string saleOrderCode = this.txtSaleOrderCode.Text;
                    string saleOrderCodeStatus = this.txtSaleOrderStatus.Text;
                    if (saleOrderCodeStatus == "")//Tao moi
                    {

                        if (txtSaleOrderRequest.Text != "")//tao don hang tu don dat hang
                        {
                            var sor = db.SaleOrderRequests.FirstOrDefault(a => a.SaleOrderRequestCode == txtSaleOrderRequest.Text);
                            sor.Status = 'C';
                            sor.LastUpdatedBy = Session["UserName"].ToString();
                            sor.LastUpdatedDateTime = DateTime.Now;
                            db.Update<SaleOrderRequest>(sor);
                            saleOrder.SaleOrderRequestID = int.Parse(ViewState["SaleOrderRequestID"].ToString());
                        }
                        db.Insert<SaleOrder>(saleOrder);
                    }
                    else // Cap nhat
                    {
                        //db.Update<SaleOrder>(saleOrder);
                        DeletePromotion(saleOrder.ID);
                        DeleteDetail(saleOrder.ID);
                        DeleteConvertHistory(saleOrder.ID, saleOrder.CustomerID);
                    }
                    updateStatus('N', saleOrder);
                    //chi tiet sp
                    List<SaleOrderDetail> listDetail = new List<SaleOrderDetail>();
                    foreach (GridDataItem it in gvData.Items)
                    {
                        SaleOrderDetail soDetail = new SaleOrderDetail();
                        soDetail.SaleOrderID = saleOrder.ID;
                        soDetail.ProductID = int.Parse(it["ProductID"].Text);
                        soDetail.Price = double.Parse(it["Price"].Text);
                        soDetail.PackType = int.Parse(it["PackType"].Text);
                        soDetail.Quantity = int.Parse(it["Quantity"].Text);
                        //soDetail.PurchasePrice
                        double? PurchasePrice = (from w in db.Warehouses where w.ProductID == int.Parse(it["ProductID"].Text) && w.PackType == soDetail.PackType && w.ShopID == int.Parse(this.cboShop.SelectedValue) select w.PurchasePrice).FirstOrDefault();
                        soDetail.PurchasePrice = PurchasePrice;
                        double weight = double.Parse(it["Weight"].Text.Replace(",", ""));
                        soDetail.Weight = weight;
                        soDetail.Amount = double.Parse(it["Price"].Text) * weight;
                        soDetail.CreatedBy = Session["UserName"].ToString();
                        soDetail.LastUpdatedBy = Session["UserName"].ToString();
                        soDetail.CreatedDateTime = DateTime.Now;
                        soDetail.LastUpdatedDateTime = DateTime.Now;
                        soDetail.Status = 'N';

                        listDetail.Add(soDetail);
                    }
                    db.Insert<SaleOrderDetail>(listDetail);
                    //Insert KM 
                    InsertPromotion(saleOrder.ID);
                    //Insert lich su quy doi
                    InsertConvertHistory(saleOrder.ID, saleOrder.CustomerID);

                    db.SubmitChanges();
                    transation.Complete();
                    this.txtSaleOrderCode.Text = saleOrder.SaleOderCode;
                    this.txtSaleOrderCode.ReadOnly = true;
                    this.txtCustomerCode.ReadOnly = true;
                    this.txtCustomerName.ReadOnly = true;
                    JavascriptUtil.LoadMessage(UpdatePanel1, true, "Thành công");
                    TabStrip1.SelectedIndex = 0;
                    RadPageView1.Selected = true;
                }
                else
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Danh sách sản phẩm không được trống");
                }
            }
            catch (Exception ex)
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
                ControlUtil.LogError("-----------------------------");
                ControlUtil.LogError("SaleOrder-btnSave_Click");
                ControlUtil.LogError(ex.ToString());
                ControlUtil.LogError("-----------------------------");
                return;
            }
        }
    }

    protected void btnDelivery_Click(object sender, EventArgs e)
    {
        if (this.cboFormReceipt.SelectedValue.ToLower() != "s")//Tại cưa hàng
        {
            //var saleOrder = db.SaleOrders.FirstOrDefault<SaleOrder>(s => s.SaleOderCode == txtSaleOrderCode.Text);
            SaleOrder saleOrder = createSaleOrderObj();
            updateStatus('T', saleOrder);
        }
    }
    protected void btnPayment_Click(object sender, EventArgs e)
    {
        try
        {
            this.btnPayment.Enabled = false;
            if (CheckPromotionSelect() == true)
            {
                SaleOrder saleOrder = createSaleOrderObj();
                if (saleOrder.Status != 'C')//da thanh toan roi khong duoc thanh toan nua
                {
                    saleOrder.PaymentDateTime = DateTime.Now;
                    updateStatus('C', saleOrder);
                }
                else
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Đơn hàng này đã được thanh toán");
                    ControlUtil.LogError("-----------------------------");
                    ControlUtil.LogError("SaleOrder-btnPayment_Click- SaleOrderCode:"+saleOrder.SaleOderCode+" double payment");
                    ControlUtil.LogError("-----------------------------");
                }
            }
            else
            {
                this.btnPayment.Enabled = true;
            }
        }catch(Exception ex){
            this.btnPayment.Enabled = true;
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-btnPayment_Click");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        var saleOrder = db.SaleOrders.FirstOrDefault<SaleOrder>(s => s.SaleOderCode == txtSaleOrderCode.Text);
        if (saleOrder.SaleOrderRequestID != 0)
        {
            var saleOrderRequest = db.SaleOrderRequests.FirstOrDefault<SaleOrderRequest>(a => a.ID == saleOrder.SaleOrderRequestID);
            if (saleOrderRequest != null)
            {
                saleOrderRequest.Status = 'N';
                saleOrderRequest.LastUpdatedDateTime = DateTime.Now;
                saleOrderRequest.LastUpdatedBy = Session["UserName"].ToString();
                db.Update<SaleOrderRequest>(saleOrderRequest);
            }
        }
        updateStatus('E', saleOrder);
    }
    protected void btnReturn_Click(object sender, EventArgs e)
    {
        var saleOrder = db.SaleOrders.FirstOrDefault<SaleOrder>(s => s.SaleOderCode == txtSaleOrderCode.Text);
        if (saleOrder != null && saleOrder.Status != 'R')//chi duoc tra hang 1 lan
        {
            updateStatus('R', saleOrder);
        }
        else
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Đơn hàng này đã được trả hàng");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-btnReturn_Click- SaleOrderCode:" + saleOrder.SaleOderCode + " double return");
            ControlUtil.LogError("-----------------------------");
        }
    }

    private bool CheckPromotionSelect()
    {
        bool result = true;
        try
        {
            //check da chon sp KM chua
            foreach (GridDataItem it in gvPromotion.Items)
            {
                if (int.Parse(it["PromotionQuantity"].Text) > 0)
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn sản phẩm quà tặng");
                    TabStrip1.SelectedIndex = 2;
                    RadPageView3.Selected = true;
                    return result = false;
                }
                else if (int.Parse(it["PromotionQuantity"].Text) < 0)
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Sản phẩm " + it["ProductName"].Text + ". Số lượng chọn không được vượt quá số lượng khuyến mãi");
                    return result = false;
                }
            }
        }catch(Exception ex){
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-CheckPromotionSelect");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
            return result = false;
        }
        return result;
    }

    private void updateStatus(char status, SaleOrder saleOrder)
    {

        try
        {
            bool result = true;
            if (saleOrder != null)
            {
                char? StatusBeforeReturn = saleOrder.Status;
                saleOrder.Status = status;

                saleOrder.LastUpdatedBy = Session["UserName"].ToString();
                saleOrder.LastUpdatedDateTime = DateTime.Now;

                if (status == 'C')//Hoan tat
                {
                    result = InOutWarehouse("O", saleOrder);
                }
                else if (status == 'R')//Tra hang va o trang thai da thanh toan thi  return lai so luong
                {
                    saleOrder.StatusBeforeReturn = StatusBeforeReturn;
                    if (StatusBeforeReturn == 'C')
                    {
                        result = InOutWarehouse("I", saleOrder);
                    }
                }
                if (result == true)
                {
                    db.Update<SaleOrder>(saleOrder);
                    db.SubmitChanges();
                    dispalyButton(saleOrder.Status, saleOrder.FormReceipt);
                }
                else
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Lỗi, thất bại. vui lòng thử lại hoặc liên hệ admin");
                    return;
                }
                JavascriptUtil.LoadMessage(UpdatePanel1, true, "Thành công!");
            }
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-updateStatus");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    

    //Tru kho -->ban hang, cong kho-->Tra hang
    private bool InOutWarehouse(string type, SaleOrder saleOrder)
    {
        bool result = true;
        //Có 2 loại trả hàng: 1. trả hàng khi đã thanh toán, trả hàng khi đang giao hàng
        if (type == "O")// ban hang
        {
            try
            {
                //Tru kho sp ban
                List<Warehouse> listWarehouse = new List<Warehouse>();
                var listSaleOrderDetail = (from l in db.SaleOrderDetails
                                           join p in db.Products on l.ProductID equals p.ID
                                           where l.SaleOrderID == saleOrder.ID && p.Status == 'A'
                                           select new
                                           {
                                               l.ProductID,
                                               l.PackType,
                                               l.Quantity,
                                               p.ProductName
                                           }).ToList();
                foreach (var soDetail in listSaleOrderDetail)
                {
                    var warehouse = db.Warehouses.FirstOrDefault<Warehouse>(w => w.ProductID == soDetail.ProductID && w.PackType == soDetail.PackType && w.Status == 'A' && w.ShopID == saleOrder.ShopID);
                    if (warehouse == null)
                    {
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Sản phẩm " + soDetail.ProductName + " không tồn kho!");
                        return result = false;
                    }
                    int? RemainQty = warehouse.Quantity - IntOrNull(soDetail.Quantity);
                    warehouse.Quantity = RemainQty;
                    warehouse.RefCode = saleOrder.SaleOderCode;
                    warehouse.RefType = "Bán hàng";
                    warehouse.Remark = "SaleOrder-SaleOrderDetail";
                    if (warehouse.Quantity < 0)
                    {
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "số lượng gạo " + soDetail.ProductName + " tồn kho không đủ, vui lòng kiểm tra lại số lượng gạo tồn kho");
                        return result = false;
                    }
                    warehouse.LastUpdatedBy = Session["UserName"].ToString();
                    warehouse.LastUpdatedDateTime = DateTime.Now;
                    if (warehouse.Quantity == 0)
                    {
                        warehouse.PurchasePrice = 0;
                    }
                    listWarehouse.Add(warehouse);
                }
                //update trang thai SaleOrderPromotion va tru kho sp qua tang
                List<Warehouse> listWarehousePro = new List<Warehouse>();
                List<SaleOrderPromotion> listSaleOrderPromotion = (from l in db.SaleOrderPromotions join p in db.Products on l.ProductID equals p.ID where l.SaleOrderID == saleOrder.ID && p.Status != 'C' select l).ToList<SaleOrderPromotion>();
                foreach (SaleOrderPromotion sop in listSaleOrderPromotion)
                {
                    //Update trang thai hoan tat
                    sop.Status = 'C';
                    sop.LastUpdatedBy = Session["UserName"].ToString();
                    sop.LastUpdatedDateTime = DateTime.Now;
                    //Tru kho SP Qua tang
                    var Warehouse = db.Warehouses.FirstOrDefault(w => w.ProductID == sop.ProductID && w.Status == 'A' && w.ShopID == saleOrder.ShopID);

                    if (Warehouse == null)
                    {
                        var product = db.Products.FirstOrDefault<Product>(p => p.ID == sop.ProductID && p.Status == 'A');
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Quà tặng " + product.ProductName + " không tồn kho!");
                        return result = false;
                    }

                   
                    int? RemainQty = Warehouse.Quantity - sop.QuantitySelect;

                    ControlUtil.Log("-----------Ban hang - Tru kho SP KM------------------");
                    ControlUtil.Log("SaleOrderId:" + sop.SaleOrderID.ToString() + ", ShopID:" + saleOrder.ShopID.ToString()+ ", ProductID:" + sop.ProductID.ToString() + ", Quantity:" + sop.QuantitySelect + ",WarehouseQtyPre:" + Warehouse.Quantity.ToString() + ",WarehouseQtyLast:" + RemainQty.ToString());

                    Warehouse.Quantity = RemainQty;
                    Warehouse.RefCode = saleOrder.SaleOderCode;
                    Warehouse.RefType = "Bán hàng";
                    Warehouse.Remark = "SaleOrder-SaleOrderPromotion";
                    if (Warehouse.Quantity < 0)
                    {
                        var product = db.Products.FirstOrDefault<Product>(p => p.ID == sop.ProductID && p.Status == 'A');
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "số lượng quà tặng " + product.ProductName + " tồn kho không đủ, vui lòng kiểm tra lại tồn kho quà tặng");
                        return result = false;
                    }
                    if (Warehouse.Quantity == 0)
                    {
                        Warehouse.PurchasePrice = 0;
                    }
                    Warehouse.LastUpdatedBy = Session["UserName"].ToString();
                    Warehouse.LastUpdatedDateTime = DateTime.Now;
                    listWarehousePro.Add(Warehouse);
                   
                }

                ///Update diem tich luy cho khach hang
                var cus = db.Customers.FirstOrDefault(c => c.CustomerCode == this.txtCustomerCode.Text);
                if (cus == null)
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Khách hàng không tồn tại");
                    return result = false;
                }
                //cus.AccumulateAmount = cus.AccumulateAmount + double.Parse(DivAccumulateAmount.InnerText);
                cus.AccumulateAmount = cus.AccumulateAmount + saleOrder.Amount;
                cus.ConvertedAmount = cus.ConvertedAmount + double.Parse(DivConvertedAmount.InnerText);
                cus.RemainAmount = cus.AccumulateAmount - cus.ConvertedAmount;
                cus.LastUpdatedBy = Session["UserName"].ToString();
                cus.LastUpdatedDateTime = DateTime.Now;

                //Update lich su tich luy
                ConvertHistory convertHistory = db.ConvertHistories.FirstOrDefault<ConvertHistory>(h => h.SaleOrderID == saleOrder.ID && h.CustomerID == saleOrder.CustomerID);
                if (convertHistory != null)
                {
                    convertHistory.Status = 'C';
                    convertHistory.LastUpdatedBy = Session["UserName"].ToString();
                    convertHistory.LastUpdatedDateTime = DateTime.Now;

                    db.Update<ConvertHistory>(convertHistory);
                }
                db.Update<Customer>(cus);
                db.Update<SaleOrderPromotion>(listSaleOrderPromotion);
                db.Update<Warehouse>(listWarehousePro);
                db.Update<Warehouse>(listWarehouse);
            }

            catch (Exception ex)
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
                ControlUtil.LogError("-----------------------------");
                ControlUtil.LogError("SaleOrder-InOutWarehouse-Payment");
                ControlUtil.LogError(ex.ToString());
                ControlUtil.LogError("-----------------------------");
                return result = false;
            }
        }
        else//tra hang
        {
            try
            {
                //Tra so luong sp bán ve kho
                List<SaleOrderDetail> listSaleOrderDetail = (from l in db.SaleOrderDetails where l.SaleOrderID == saleOrder.ID select l).ToList<SaleOrderDetail>();
                List<Warehouse> listWarehouse = new List<Warehouse>();
                foreach (SaleOrderDetail soDetail in listSaleOrderDetail)
                {
                    var warehouse = db.Warehouses.FirstOrDefault<Warehouse>(w => w.ProductID == soDetail.ProductID && w.PackType == soDetail.PackType && w.Status == 'A' && w.ShopID == saleOrder.ShopID);
                    if (warehouse == null)
                    {
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Sản phẩm không tồn kho!");
                        return result = false;
                    }
                    //neu gia von = 0 thi lay gia von cua chi tiet ban hang
                    if (warehouse.Quantity == 0)
                    {
                        warehouse.PurchasePrice = soDetail.PurchasePrice;
                    }
                    warehouse.RefCode = saleOrder.SaleOderCode;
                    warehouse.RefType = "Trả đon hàng bán";
                    warehouse.Remark = "SaleOrder-SaleOrderDetail";
                    warehouse.Quantity = warehouse.Quantity + IntOrNull(soDetail.Quantity);
                    warehouse.LastUpdatedBy = Session["UserName"].ToString();
                    warehouse.LastUpdatedDateTime = DateTime.Now;

                    listWarehouse.Add(warehouse);
                }

                //update va TRa so luong sp qua tang ve kho
                List<Warehouse> listWarehousePro = new List<Warehouse>();
                List<SaleOrderPromotion> listSaleOrderPromotion = (from l in db.SaleOrderPromotions where l.SaleOrderID == saleOrder.ID  && l.Status != 'R' select l).ToList<SaleOrderPromotion>();

                foreach (SaleOrderPromotion sop in listSaleOrderPromotion)
                {
                    sop.Status = 'R';
                    sop.LastUpdatedBy = Session["UserName"].ToString();
                    sop.LastUpdatedDateTime = DateTime.Now;

                    var warehouse = db.Warehouses.FirstOrDefault<Warehouse>(w => w.ProductID == sop.ProductID && w.Status == 'A' && w.ShopID == saleOrder.ShopID);
                    if (warehouse == null)
                    {
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Quà tặng không tồn kho!");
                        return result = false;
                    }
                   
                    if (warehouse.Quantity == 0)
                    {
                        warehouse.PurchasePrice = sop.PurchasePrice;
                    }

                    int? RemainQty = warehouse.Quantity + sop.QuantitySelect;
                    ControlUtil.Log("-----------Tra don hang - Cong kho SP KM------------------");
                    ControlUtil.Log("SaleOrderId:" + sop.SaleOrderID.ToString() + ", ShopID:" + saleOrder.ShopID.ToString()+ ", ProductID:" + sop.ProductID.ToString() + ", Quantity:" + sop.QuantitySelect + ",WarehouseQtyPre:" + warehouse.Quantity.ToString() + ",WarehouseQtyLast:" + RemainQty.ToString());
                    warehouse.RefCode = saleOrder.SaleOderCode;
                    warehouse.RefType = "Trả đon hàng bán";
                    warehouse.Remark = "SaleOrder-SaleOrderPromotion";
                    warehouse.Quantity = RemainQty;
                    warehouse.LastUpdatedBy = Session["UserName"].ToString();
                    warehouse.LastUpdatedDateTime = DateTime.Now;
                    listWarehousePro.Add(warehouse);
                }

                //tru tong tien tich luy
                var cus = db.Customers.FirstOrDefault(c => c.CustomerCode == this.txtCustomerCode.Text);
                if (cus == null)
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Khách hàng không tồn tại");
                    return result = false;
                }
                //cus.AccumulateAmount = cus.AccumulateAmount - double.Parse(DivAccumulateAmount.InnerText);
                cus.AccumulateAmount = cus.AccumulateAmount - saleOrder.Amount;
                cus.ConvertedAmount = cus.ConvertedAmount - double.Parse(DivConvertedAmount.InnerText);
                cus.RemainAmount = cus.AccumulateAmount - cus.ConvertedAmount;
                cus.LastUpdatedBy = Session["UserName"].ToString();
                cus.LastUpdatedDateTime = DateTime.Now;

                //Update lich su tich luy
                ConvertHistory convertHistory = db.ConvertHistories.FirstOrDefault<ConvertHistory>(h => h.SaleOrderID == saleOrder.ID && h.CustomerID == saleOrder.CustomerID);
                if (convertHistory != null)
                {
                    convertHistory.Status = 'R';
                    convertHistory.LastUpdatedBy = Session["UserName"].ToString();
                    convertHistory.LastUpdatedDateTime = DateTime.Now;
                    db.Update<ConvertHistory>(convertHistory);
                }

                db.Update<SaleOrderPromotion>(listSaleOrderPromotion);
                db.Update<Warehouse>(listWarehousePro);
                db.Update<Warehouse>(listWarehouse);
                db.Update<Customer>(cus);

            }
            catch (Exception ex)
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
                ControlUtil.LogError("-----------------------------");
                ControlUtil.LogError("SaleOrder-InOutWarehouse-Return");
                ControlUtil.LogError(ex.ToString());
                ControlUtil.LogError("-----------------------------");
                return result = false;
            }
        }
        return result;
        //db.SubmitChanges();
    }

    //Load lai chuong trinh KM
    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        int totalWeight = Convert.ToInt32(sumWeight.InnerText);
        DataTable dtPro = loadPromotionPromotion(totalWeight, 0);
        bindingPromotion(dtPro);

        /*
        btnPayment.Enabled = false;
        btnReturn.Enabled = false;
        btnDelivery.Enabled = false;
        */ 
    }

    /*Khach hang*/
    private void LoadFormForCustomerTab()
    {
        Utils.loadLocation(cboProvince, 0, 1, 0);
        //Utils.loadLocation(cboDistrict, int.Parse(cboProvince.SelectedValue), 1, 0);
        gv.DataSource = new DataTable();
        gv.DataBind();
    }

    protected void gv_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        Loaddata();

    }
    private void Loaddata()
    {
        DBDataContext db = LINQUtil.GetDBWriteOnly();

        String CustomerCode = Utils.KillChars(this.txtCustomerCodeNew.Text.Trim());
        String CustomerName = Utils.KillChars(this.txtCustomerNameNew.Text.Trim());
        String CustomerPhone = Utils.KillChars(this.txtPhoneNumber.Text.Trim());
        int PageNumber = gv.CurrentPageIndex + 1;
        int PageSize = gv.PageSize;

        var q = db.Customer_Search(CustomerCode, CustomerName, CustomerPhone, "", 0, 0, PageSize, PageNumber).ToList();
        if (q.Count > 0)
        {
            gv.ClientSettings.Scrolling.UseStaticHeaders = true;
            gv.VirtualItemCount = q[0].TotalRows.Value;
            gv.DataSource = q;
            if (q.Count > 5)
            {
                //gv.Height = 120;
                gv.ClientSettings.Scrolling.AllowScroll = true;
            }
        }
        else
        {
            gv.DataSource = new DataTable();
        }
    }

    protected void btnCusSave_Click(object sender, EventArgs e)
    {
        Customer cus = createCustomer("1");
        if (cus != null)
        {
            String DistrictName = cboDistrict.SelectedItem.Text;
            String ProvinceName = cboProvince.SelectedItem.Text;
            string AddressFull = cus.Address + ", " + DistrictName + ", " + ProvinceName;
           
            this.txtReceiptPerson.Text = cus.CustomerName;
            this.txtReceiptPhoneNumer.Text = cus.PhoneNumber;
            this.txtReceiptAdress.Text = AddressFull;

            TabStrip1.SelectedIndex = 0;
            RadPageView1.Selected = true;
            this.txtCustomerName.Enabled = false;
            JavascriptUtil.LoadMessage(UpdatePanel1, true, "Tạo khách hàng thành công!");
        }
    }
    protected Customer createCustomer(string cusType)
    {
        try
        {
            //DBDataContext dbread = LINQUtil.GetDBWriteOnly();
            Customer customer = new Customer();

            String CustomerName = "";
            String CustomerPhone = "";
            String Address = "";
            int DistrictID = 0;
            int ProvinceID = 0;
            if (cusType == "1")
            {
                CustomerName = Utils.KillChars(this.txtCustomerNameNew.Text.Trim());
                CustomerPhone = Utils.KillChars(this.txtPhoneNumber.Text.Trim());
                Address = Utils.KillChars(this.txtAddress.Text.Trim());
                DistrictID = Convert.ToInt32(this.cboDistrict.SelectedValue == "" ? "0" : this.cboDistrict.SelectedValue);
                ProvinceID = Convert.ToInt32(this.cboProvince.SelectedValue == "" ? "0" : this.cboProvince.SelectedValue);
                customer.CustType = "KH";
                //Check khong cho phep trung do dien thoai
                var check = (from cus in db.Customers
                             where cus.PhoneNumber == CustomerPhone
                             select cus).FirstOrDefault();
                if (check != null)
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Số điện thoại: " + CustomerPhone + " đã tồn tại. vui lòng chọn số khác");
                    return null;
                }
            }
            else // Khach le
            {
                CustomerName = "Khách lẻ";
                customer.CustType = "KL";
            }
            //Lay ma sau cung
            int lenZero = 7;//So ky tu khôg tính chữ cái đưungs đầu. ví dụ KH0000001 --> 7, k tính KH
            var customerCodeMax = db.Customers.Max(d => d.OrderNumber);
            int MaxOrderNumber = (customerCodeMax == null ? 0 : Convert.ToInt32(customerCodeMax)) + 1;
            String LastCode = ("000000" + MaxOrderNumber).ToString();
            String CustomerCode = "KH" + LastCode.Substring(LastCode.Length - lenZero);
            //End

            customer.CustomerCode = CustomerCode;
            customer.CustomerName = CustomerName;
            customer.PhoneNumber = CustomerPhone;
            customer.Address = Address;
            customer.DistrictID = DistrictID;
            customer.ProvinceID = ProvinceID;
            customer.AccumulateAmount = 0;
            customer.ConvertedAmount = 0;
            customer.RemainAmount = 0;
            customer.CreatedBy = Session["UserName"].ToString();
            customer.CreatedDateTime = DateTime.Now;
            customer.LastUpdatedBy = Session["UserName"].ToString();
            customer.LastUpdatedDateTime = DateTime.Now;
            customer.Status = 'A';
            customer.OrderNumber = MaxOrderNumber;
            db.Insert<Customer>(customer);
            db.SubmitChanges();
            this.txtCustomerCodeNew.Text = customer.CustomerCode;
            this.txtCustomerCode.Text = customer.CustomerCode;
            this.txtCustomerName.Text = customer.CustomerName;

            return customer;
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra");
            ControlUtil.LogError("----------------------------");
            ControlUtil.LogError("SaleOrder-createCustomer");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("----------------------------");
            return null;
        }
    }
    protected void btnCusSearch_Click(object sender, EventArgs e)
    {
        Loaddata();
        gv.DataBind();
    }
    protected void lnkCustomerCode_Click(object sender, EventArgs e)
    {
        LinkButton LNKCustomer = (LinkButton)sender;
        GridDataItem dataItem = (GridDataItem)LNKCustomer.NamingContainer;
        String CustomerName = dataItem["CustomerName"].Text;
        String CustomerCode = LNKCustomer.Text;
        String CustomerPhone = dataItem["PhoneNumber"].Text;


        this.txtCustomerCode.Text = CustomerCode;
        this.txtCustomerName.Text = CustomerName;
        String AddressFull = dataItem["Address"].Text + ", " + dataItem["District"].Text + ", " + dataItem["Province"].Text;

        this.txtReceiptPerson.Text = CustomerName;
        this.txtReceiptPhoneNumer.Text = CustomerPhone;
        this.txtReceiptAdress.Text = AddressFull;

        TabStrip1.SelectedIndex = 0;
        RadPageView1.Selected = true;
        this.txtCustomerName.Enabled = false;
        // Session["Cus"] = CustomerCode + "@" + CustomerName;
        // ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "ClientClose2", "ClientClose2('" + CustomerCode + "','" + CustomerName + "');", true);
        //ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "ClientClose2", "ClientClose2('" + CustomerCode + "','" + CustomerName + "','" + CustomerPhone + "','" + AddressFull + "');", true);
    }
    protected void cboProvince_SelectedIndexChanged(object sender, EventArgs e)
    {
        string provinceID = cboProvince.SelectedValue;
        Utils.loadLocation(cboDistrict, int.Parse(provinceID), 0, 0);
    }
    protected void btnPrint_Click(object sender, EventArgs e)
    {
        string saleOrderCode = this.txtSaleOrderCode.Text;
        if (saleOrderCode != "")
        {
            StringBuilder content = getContent(saleOrderCode);
            ScriptManager.RegisterStartupScript(Page, this.GetType(), "printSaleOrder", "PrintSO('" + content.ToString() + "');", true);
            
        }
    }
    private StringBuilder getContent(string saleOrderCode)
    {
        StringBuilder htmlText = new StringBuilder();
        
         // Thong tin cua hàng
        var so = db.SaleOrders.FirstOrDefault<SaleOrder>(a => a.SaleOderCode == saleOrderCode);

        //thong tin cua hang
        var shop = (from s in db.Shops
                    where s.ID == so.ShopID &&
                   s.Status == 'A'
                   select s).FirstOrDefault();
        //danh sach san pham gao
        var listProduct = db.SaleOrderDetails.ToList<SaleOrderDetail>().Where(b=>b.SaleOrderID == so.ID);

        //danh sach qua tang
        var listProductPromotion = db.SaleOrderPromotions.ToList<SaleOrderPromotion>().Where(c=>c.SaleOrderID==so.ID);

        //Thong tin khach hang
        var cus = db.Customers.FirstOrDefault<Customer>(d=>d.ID == so.CustomerID);

        //ten thu ngan

        var casher = (from e in db.Employees
                      join u in db.Users on e.ID equals u.EmployeeID
                      where e.Status == 'A'
                      && u.Status == 'A'
                      && u.UserName == so.CreatedBy
                      select e.EmplyeeName).FirstOrDefault();
        htmlText.AppendFormat("<div style=\"width:380;\"><div style=\"text-align:center;\"><span style=\"text-align:center;\"><b style=\"font-size:11pt;\">GẠO QUÊ VIỆT</b><br/></span>");
         htmlText.AppendFormat("<span style=\"text-align:center;\">Đặc sản các vùng miền!</span></div><br/>");
        
        htmlText.AppendFormat("<div style=\"text-align:center;font-size:11pt\"><span>Địa chỉ: " + shop.Address + "</span><br/>");
        htmlText.AppendFormat("<span style=\"text-align:center;font-size:11pt\">ĐT: " + shop.PhoneNumber + "</span><br/><br/>");
        htmlText.AppendFormat("<span style=\"text-align:center;font-size:14pt;\">PHIẾU TÍNH TIỀN </span><br/>");
        htmlText.AppendFormat("<span style=\"text-align:center;\">" + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + "</span></div><br/><br/>");
        //danh sach san pham gao
        int number = 1;
        foreach (var product in listProduct)
        {
            htmlText.AppendFormat("<span>" + number.ToString() + ".</span>  ");
            htmlText.AppendFormat("<span>" + getProductName(product.ProductID) + "</span>   ");
            htmlText.AppendFormat("<span>" + string.Format("{0:N0}", product.Weight) + "(kg) x " + string.Format("{0:N0}", product.Price) + "d</span><br/>");
            htmlText.AppendFormat("<span>= " + string.Format("{0:N0}", product.Amount) + "d</span><br/>");
            number++;
        }

        htmlText.AppendFormat("<span>----------------------------------------------</span> <br/>");
        htmlText.AppendFormat("<span style=\"text-align:center;font-size:13pt;\">Tổng tiền: "+string.Format("{0:N0}",so.Amount) +"d</span> <br/>");
        htmlText.AppendFormat("<span style=\"text-align:center;font-size:13pt;\">Giảm hóa đơn: " + string.Format("{0:N0}",so.DiscountAmount)+ "d</span> <br/>");
        if (so.VAT > 0)
        {
            htmlText.AppendFormat("<span style=\"text-align:center;font-size:13pt;\">VAT: " + string.Format("{0:N0}",(so.Total - so.Amount)) + "d</span> <br/>");
        }
        htmlText.AppendFormat("<span style=\"text-align:center;font-size:13pt;\">Thanh toán: " + string.Format("{0:N0}",so.Total) + "d</span> <br/>");
        //Qua tang khuyen mai
        htmlText.AppendFormat("<span>----------------------------------------------</span> <br/>");
        htmlText.AppendFormat("<span>Sản phẩm quà tặng</span> <br/>");

        number = 1;
        foreach (var p in listProductPromotion)
        {
            htmlText.AppendFormat("<span>" + number.ToString() + ".</span>  ");
            htmlText.AppendFormat("<span>" + getProductName(p.ProductID) + "</span>   ");
            htmlText.AppendFormat("<span>SL: " + p.QuantitySelect.ToString() + "</span><br/>");
            number++;
        }
        //khach hang
        htmlText.AppendFormat("<span>----------------------------------------------</span> <br/>");
        htmlText.AppendFormat("<span>Khách hàng: "+cus.CustomerName+"</span> <br/>");
        htmlText.AppendFormat("<span>Mã khách hàng: " + cus.CustomerCode + "</span> <br/>");
        htmlText.AppendFormat("<span>Địa chỉ:" + cus.Address + "</span> <br/>");
        htmlText.AppendFormat("<span>ĐT: " + cus.PhoneNumber + "</span> <br/>");
        htmlText.AppendFormat("<span>Số dư tích lũy: " + string.Format("{0:N0}", cus.RemainAmount) + "</span> <br/>");
        htmlText.AppendFormat("<span>----------------------------------------------</span> <br/>");
        //thu ngan
        htmlText.AppendFormat("<span>Thu ngân: " +casher+"</span> <br/>");
        htmlText.AppendFormat("<span>Số hóa đơn: " + so.SaleOderCode + "</span> <br/><br/>");

        //thong tin cong ty
        htmlText.AppendFormat("<span style=\"font-size:11pt;\">CTy TNHH MTV Lương thực Tuyên Du</span> <br/>");
        htmlText.AppendFormat("<span style=\"font-size:11pt;\">Đ/C: Ngã Tư Quang phục - Tứ kỳ - Hải Dương</span> <br/>");
        htmlText.AppendFormat("<span style=\"font-size:11pt;\">ĐT: (0320)3 519 519 Fax: (0320)3 747153</span> <br/>");
        htmlText.AppendFormat("<div style=\"font-size:11pt;\"><span>Website: gaoqueviet.com.vn</span></div> <br/>");
        htmlText.AppendFormat("<div style=\"text-align:center;\"><span style=\"text-align:center;\"><br/>");
        htmlText.AppendFormat("<span style=\"text-align:center;\"><b>Cảm ơn quý khách!</b></span> <br/>");
        htmlText.AppendFormat("<span style=\"text-align:center;\"><b>Hẹn gặp lại!</b></span></div></div>");

        return htmlText;
    }
    private string getProductName(int? ID)
    {
        var name = db.Products.FirstOrDefault<Product>(a=>a.ID == ID && a.Status =='A');
        return name.ProductName;
    }
}
 